package dao;

import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;

public class GenericoDAO {

	public void salvarAlterar(Object obj) throws Exception {
		Transaction transacao = null;
		Session sessao = null;
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			transacao = sessao.beginTransaction();
			sessao.save(obj);
			transacao.commit();
		} catch (Exception e) {
			transacao.rollback();
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			sessao.close();
		}
	}

	public Integer salvar(Object obj) throws Exception {
		Transaction transacao = null;
		Session sessao = null;
		Integer codigo = 0;
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			transacao = sessao.beginTransaction();
			codigo = (Integer) sessao.save(obj);
			transacao.commit();
		} catch (Exception e) {
			transacao.rollback();
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			sessao.close();
		}
		return codigo;
	}

	public void alterar(Object obj) throws Exception {
		Transaction transacao = null;
		Session sessao = null;
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			transacao = sessao.beginTransaction();
			sessao.update(obj);
			transacao.commit();
		} catch (Exception e) {
			transacao.rollback();
			e.printStackTrace();
			System.out.println(e.getMessage());
		} finally {
			sessao.close();
		}
	}

	public void excluir(Object obj) throws Exception {
		Transaction transacao = null;
		Session sessao = null;
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			transacao = sessao.beginTransaction();
			sessao.delete(obj);
			transacao.commit();
		} catch (Exception e) {
			transacao.rollback();
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			sessao.close();
		}
	}
}